package cn.itcast.service.cargo.impl;

import cn.itcast.dao.cargo.ExportDao;
import cn.itcast.dao.cargo.ExportProductDao;
import cn.itcast.dao.cargo.PackingListDao;
import cn.itcast.domain.cargo.Export;
import cn.itcast.domain.cargo.PackingList;
import cn.itcast.service.cargo.PackingService;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.UUID;

@Service(timeout = 100000)
public class PackingServiceImpl implements PackingService {
    @Autowired
    private PackingListDao packingListDao;
    @Autowired
    private ExportDao exportDao;

    @Override
    public PackingList findBypackingId(String id) {
        PackingList packingList = packingListDao.selectByPrimaryKey(id);
        return packingList;

    }

    @Override
    public void save(PackingList packingList, String contractIds) {
        packingList.setPackingListId(UUID.randomUUID().toString());
        packingList.setState(0L);
        packingList.setExportIds(contractIds);
        //遍历装箱单的报运单合同号修改状态为已装箱
        String split = packingList.getExportIds();
        String[] exportIds = split.split(",");
        if(exportIds!=null&&exportIds.length>0){
            for (String exportId : exportIds) {
                Export export = exportDao.selectByPrimaryKey(exportId);
                export.setState(4);
                exportDao.updateByPrimaryKeySelective(export);
            }
        }
        packingListDao.insertSelective(packingList);
    }

    @Override
    public PageInfo<PackingList> findAll(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<PackingList> lists = packingListDao.selectByExample(null);
        return new PageInfo<>(lists);
    }

    @Override
    public void delete(String id) {
        //根据装箱单id查询装箱单对象
        PackingList packingList = packingListDao.selectByPrimaryKey(id);
        String spilt = packingList.getExportIds();
        String[] exportIds = spilt.split(",");
        if (exportIds != null && exportIds.length > 0) {
            //遍历每个报运单id并修改报运单状态
            for (String exportId : exportIds) {
                Export export = exportDao.selectByPrimaryKey(exportId);
                export.setState(2);
                exportDao.updateByPrimaryKeySelective(export);
            }
        }
        packingListDao.deleteByPrimaryKey(id);
    }

    @Override
    public long findStateById(String id) {
        PackingList packingList = packingListDao.selectByPrimaryKey(id);
        Long state = packingList.getState();
        return state;
    }
}
